package redispool

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/astaxie/beego"
	log "github.com/astaxie/beego/logs"
	"github.com/garyburd/redigo/redis"
)

const (
	ssrcTimeOutInSeconds = 600
)

var (
	// 定义常量
	RedisClient *redis.Pool
)

func Init(host string, db int) {

	log.Debug("start to connect redis:%v,index:%v", host, db)
	// 建立连接池
	RedisClient = &redis.Pool{
		// 从配置文件获取maxidle以及maxactive，取不到则用后面的默认值
		MaxIdle:     2,
		MaxActive:   10,
		IdleTimeout: 180 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", host)
			if err != nil {
				return nil, err
			}
			// 选择db
			c.Do("SELECT", db)
			return c, nil
		},
	}

}

func SetWithExpair(key, expair string, value []byte) error {

	rc := RedisClient.Get()
	defer rc.Close()

	if ok, err := redis.Bool(rc.Do("SET", key, value, "EX", expair)); ok {
		return nil
	} else {
		return err
	}
}

func GetValue(key string) ([]byte, error) {

	rc := RedisClient.Get()
	defer rc.Close()

	return redis.Bytes(rc.Do("GET", key))
}

type SsrcSsion struct {
	Ssrc     string `json:"ssrc"`
	KernelId string `json:kernel`
}

func SaveSsrc(ssrc, dsid int) error {

	obj := SsrcSsion{
		Ssrc:     fmt.Sprintf("%d", ssrc),
		KernelId: fmt.Sprintf("%d", dsid),
	}

	value, err := json.Marshal(obj)
	if err != nil {
		beego.Error("json marshal err", err)
		return err
	}

	rc := RedisClient.Get()
	defer rc.Close()

	if rc == nil {
		beego.Error("redis connnection is nil")
		return errors.New("redis connnection is nil")

	}

	beego.Info("send data", ssrc, value)

	_, err = rc.Do("SET", obj.Ssrc, value, "EX", ssrcTimeOutInSeconds)
	if err != nil {
		return err
	}

	return nil
}

func GetSsrcSession(ssrc int) (*SsrcSsion, error) {

	rc := RedisClient.Get()
	defer rc.Close()

	if rc == nil {
		beego.Error("redis connnection is nil")
		return nil, errors.New("redis connnection is nil")

	}

	ssrcStr := fmt.Sprintf("%d", ssrc)

	valueBytes, err := redis.Bytes(rc.Do("GET", ssrcStr))
	if err != nil {
		return nil, err
	}

	session := SsrcSsion{}
	err = json.Unmarshal(valueBytes, &session)
	if err != nil {
		return nil, err
	}

	return &session, nil

}
